package com.madev.isellcrazyitems;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import com.madev.isellcrazyitems.adapter.ImageAdapter;
import com.madev.isellcrazyitems.entity.Product;
import com.madev.isellcrazyitems.entity.Reservation;
import com.madev.isellcrazyitems.entity.User;
import com.madev.isellcrazyitems.handler.JSONController;
import com.madev.isellcrazyitems.handler.DatabaseHandler;
import com.madev.sales.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.NumberPicker;
import android.widget.Toast;

public class Purchase extends Activity {
	//private Item item = new Item();
	private User customer = new User();
	private GridView mainGV;
    private ProgressDialog pDialog = null;
    private JSONController jController = new JSONController();
    private static String item_url = "http://unifiq.5kportal.com/retrieve_item.php";
    private static String customer_url = "http://unifiq.5kportal.com/retrieve_customer.php";
    private static final String TAG_SUCCESS = "success", TAG_ITEM = "item", TAG_ID = "id", TAG_NAME = "name", TAG_IMG_PATH = "imgPath", TAG_QUANTITY = "quantity", TAG_PRICE = "price", TAG_CUSTOMER = "customer", TAG_USER_ID = "uid", TAG_USER_NAME = "name", TAG_PASSWORD = "password", TAG_CREATION_DATE = "creationDate";
    private JSONArray itemJArr = null, customerJArr = null;
    private ArrayList<Integer> itemArr = new ArrayList<Integer>(), qtyArr = new ArrayList<Integer>();
	private ArrayList<Product> prodArr = new ArrayList<Product>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.purchase_layout);
		
	    if (android.os.Build.VERSION.SDK_INT > 9) {
	        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	        StrictMode.setThreadPolicy(policy);
	      }
	    
        Bundle bundle = getIntent().getExtras();
        
        try{
	        itemArr = bundle.getIntegerArrayList("itemArr");
	        qtyArr = bundle.getIntegerArrayList("qtyArr");
        }
        catch (Exception e){
        	e.printStackTrace();
        }
        
	    new LoadAllItem().execute();
	}
	
    @Override
    public void onPause()
    {
        super.onPause();
        if(pDialog != null)
            pDialog.dismiss();
    }
    
    class LoadAllItem extends AsyncTask<String, String, String> {
    	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Purchase.this);
            pDialog.setMessage("Loading page. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        @Override
		protected String doInBackground(String... args) {
        	//retrieving from local database;
        	
        	DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
        	prodArr = handler.getProducts();
        	
        	customer = handler.getLogin();
        	//retrieving from online database
        	
            /*List<NameValuePair> itemParams = new ArrayList<NameValuePair>();
            JSONObject itemObj = jController.makeHttpRequest(item_url, "GET", itemParams);
            
            List<NameValuePair> customerParams = new ArrayList<NameValuePair>();
            customerParams.add(new BasicNameValuePair(TAG_USER_ID, "34"));
            JSONObject customerObj = jController.makeHttpRequest(customer_url, "GET", customerParams);
 
            try {
                int success = itemObj.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    itemJArr = itemObj.getJSONArray(TAG_ITEM);

                    for (int i = 0; i < itemJArr.length(); i++) {
                        JSONObject jObject = itemJArr.getJSONObject(i);
                        item.setId(jObject.getInt(TAG_ID));
                        item.setName(jObject.getString(TAG_NAME));
                        item.setImgPath(jObject.getString(TAG_IMG_PATH));
                        item.setQuantity(jObject.getInt(TAG_QUANTITY));
                        item.setPrice(jObject.getDouble(TAG_PRICE));
                    	
                    }
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            
            
            try {
                int success = customerObj.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    customerJArr = customerObj.getJSONArray(TAG_CUSTOMER);
    				
    				for (int i = 0; i < customerJArr.length(); i++) {
                        JSONObject jObject = customerJArr.getJSONObject(i);  	
                        
                        customer.setUserId(jObject.getInt(TAG_USER_ID));
                        customer.setUserFullName(jObject.getString(TAG_USER_NAME));        
                    	
                    }
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            */
            
            return null;      

        }
        
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
		protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
				public void run() {
            		
            		mainGV = (GridView) findViewById(R.id.main_gv);	 
            		mainGV.setAdapter(new ImageAdapter(Purchase.this, prodArr));

            		mainGV.setOnItemClickListener(new OnItemClickListener() {
            			@Override
						public void onItemClick(AdapterView<?> parent, View v,
            					int position, long id) {         				
            				
            		        AlertDialog.Builder builder = new AlertDialog.Builder(Purchase.this);
            		        final int itemID = Integer.valueOf(prodArr.get(position).getProductID());
            		        int itemQty = Integer.valueOf(prodArr.get(position).getProductStock());
            		        
           					if (!itemArr.isEmpty()){
            					for (int i = 0; i < itemArr.size(); i++){
            						if (itemArr.get(i) == Integer.valueOf(prodArr.get(position).getProductID())){
            							itemQty -= qtyArr.get(i);
            						}
            					}
        					}
            		        
            				if (itemQty == 0)
            				{
            					/*
            			        builder.setMessage("We apologize but the selected item is out of stock at the moment. Please try again at a later date.")
            		               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            		                   @Override
									public void onClick(DialogInterface dialog, int id) {
            		                   }
            		               });		
            		               
        		               */
            		                  
            					
            					final NumberPicker np = new NumberPicker(Purchase.this);
            					
            					np.setMaxValue(100);
            					np.setMinValue(1);
            					builder.setView(np);
            					
            			        builder.setMessage("This item is Out-Of-Stock at the moment. If you would like to reserve, please enter the amount.")
            		               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            		                   @Override
									public void onClick(DialogInterface dialog, int id) {
            		                	   DatabaseHandler db = new DatabaseHandler(getApplicationContext());
            		                	   User u = db.getLogin();
            		                	   
            		                	   Reservation r = new Reservation();
            		                	   r.setProductIdNo(Integer.toString(itemID));
            		                	   r.setUserEmail(u.getUserEmail());
            		                	   r.setQuantity(np.getValue());
            		                	   
            		                	   Log.d("test", itemID + " " + u.getUserId() + " " + np.getValue());
            		                	   
            		                	   
            		                	   if(db.addReservation(r))
            		                	   {
            		                		   Toast.makeText(getApplicationContext(), 
            		                                   "Reservation success!", Toast.LENGTH_LONG).show();
            		                	   }
            		                	   else 
            		                	   {
            		                		   Toast.makeText(getApplicationContext(), 
            		                                   "Reservation unsuccessful", Toast.LENGTH_LONG).show();
            		                	   }
            		                	   
            		                   }
            		               })
            			        
         		               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        		                   @Override
								public void onClick(DialogInterface dialog, int id) {
        		                	   
        		                   }
        		                });
            			        
            				}
            				
            				else{
            					final NumberPicker np = new NumberPicker(Purchase.this);
            					
            					np.setMaxValue(itemQty);
            					np.setMinValue(1);
            					builder.setView(np);
            					
            			        builder.setMessage("How many do you want to purchase?")
            		               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            		                   @Override
									public void onClick(DialogInterface dialog, int id) {
            		                	   itemArr.add(itemID);
            		                	   qtyArr.add(np.getValue());
            		                   }
            		               })
            			        
         		               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        		                   @Override
								public void onClick(DialogInterface dialog, int id) {
        		                	   
        		                   }
        		                });
        		                   
            				}
            				
            		        builder.create().show();
             
            			}
            		});

                }
            });
 
        }
 
    }

  

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.purchase, menu);
		return true;
	}
	
	@SuppressLint("SimpleDateFormat")
	public Date stringToDate(String date) throws ParseException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.parse(date);
	}
	
	@Override
	public boolean onOptionsItemSelected (MenuItem item){
		Bundle b = new Bundle();
		b.putSerializable("customer", customer);
		b.putIntegerArrayList("itemArr", itemArr);
		b.putIntegerArrayList("qtyArr", qtyArr);
		
		if (item.getItemId() == R.id.menu_history){
			Intent historyScreen = new Intent(this, History.class);
			historyScreen.putExtras(b);
	        startActivity(historyScreen);
	        finish();
		}
		else if (item.getItemId() == R.id.menu_cart){
			if (itemArr.size() != 0){                
				Intent cartScreen = new Intent(this, Cart.class);
				cartScreen.putExtras(b);
		        startActivityForResult(cartScreen, 1);
				}
		}
		return true;
	}
	
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	if (requestCode == 1){
    		if (resultCode == RESULT_OK){ 	        
		       itemArr = data.getIntegerArrayListExtra("itemArr");
		       qtyArr = data.getIntegerArrayListExtra("qtyArr");
    		}
    	}
    }

}
